/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.hibernate.dao;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import org.hibernate.Session;
import ru.miit.elearning.hibernate.dto.Document;
import ru.miit.elearning.hibernate.dto.DocumentContent;
import ru.miit.elearning.hibernate.dto.DocumentContentId;

/**
 *
 * @author Cyclone
 */
public class DocumentDAO extends GenericDAO {

    public DocumentDAO(Session session) {
        super(session);
    }

    public Integer addCurriculumDocument(int curriculumId, String title) {
        Document doc = new Document();
        doc.setCurriculumLevel(curriculumId);
        doc.setTitle(title != null ? title : "Без названия");

        return (Integer) session.save(doc);
    }

    public void addDocumentVersion(Integer docId, Integer version, InputStream uploadStream, int userId, String fileName, String mime, Date date) throws IOException {
        DocumentContent content = new DocumentContent();

        if (version == null) {
            DocumentContent dc = ((Document) session.get(Document.class, docId)).getCurrentVersionContent();
            Integer currentVersion = null;
            if (dc != null) {
                currentVersion = dc.getId().getVersion();
            }
            version = 1 + (currentVersion != null ? currentVersion : 0);
        }

        content.setId(new DocumentContentId(docId, version));
        content.setAuthor(userId);
        content.setFileName(fileName);
        content.setMime(mime);
        content.setRevisionDate(date == null ? new Date(System.currentTimeMillis()) : date);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int iRead = 0;
        byte[] buffer = new byte[4096];
        while ((iRead = uploadStream.read(buffer)) > 0) {
            baos.write(buffer, 0, iRead);
        }
        byte[] baResult = baos.toByteArray();
        content.setContent(baResult);

        session.save(content);
    }
}
